package cn.ztq.test0614.receiver;

import android.Manifest;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothClass;
import android.bluetooth.BluetoothDevice;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.util.Log;

import androidx.core.app.ActivityCompat;

import java.util.HashMap;
import java.util.Map;

public class BluetoothReceiver extends BroadcastReceiver {
    private ScanListener listener;

    public BluetoothReceiver(ScanListener listener) {
        this.listener = listener;
    }

    @Override
    public void onReceive(Context context, Intent intent) {

        handleStateChanged(intent);


    }

    String bName = "";
    String actName = "";
    Map<String, BluetoothDevice> map = new HashMap();

    private void handleStateChanged(Intent intent) {
        String action = intent.getAction();
        if (!actName.contains(action)) {
            actName = actName + action;
            Log.e("dddd", "action:" + action);
        }

        switch (action) {
            case BluetoothAdapter.ACTION_DISCOVERY_STARTED:

                break;
            case BluetoothDevice.ACTION_FOUND:
                BluetoothDevice bluetoothDevice = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
                bName = bName + bluetoothDevice.getName();
                if (bluetoothDevice.getName() != null && !map.containsKey(bluetoothDevice.getAddress())) {
                    map.put(bluetoothDevice.getAddress(), bluetoothDevice);
                    listener.iScan(map);
                }

                break;
            case BluetoothAdapter.ACTION_DISCOVERY_FINISHED:
                for (Map.Entry<String, BluetoothDevice> entry : map.entrySet()) {
                    Log.e(entry.getKey(), entry.getValue().toString());

                    BluetoothClass bluetoothClass1 = entry.getValue().getBluetoothClass();
                    if (bluetoothClass1.getMajorDeviceClass()==BluetoothClass.Device.Major.AUDIO_VIDEO&&bluetoothClass1.getDeviceClass()==BluetoothClass.Device.AUDIO_VIDEO_WEARABLE_HEADSET){
                        Log.e("发现耳机", entry.getValue().getName() + ":是耳机~~~");
                    }
                    Log.e("map",entry.getValue().getName()+"----------------------");
                }
                listener.iScan(map);

                break;
            default:
                Log.e("dddd", "action: null" );
                break;
        }
    }
}
